package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.request.ChoiceCreateRequest;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.service.TemplateService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.stream.Collectors;

@WebServlet(name = "AdminChoiceServlet", value = "/admin/template/question/choice")
public class AdminChoiceServlet extends BaseServlet {
    /**
     * 设置选择题选项
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        var body = bind(req, res, ChoiceCreateRequest.class);
        if (body == null)   return;

        try {
            var question = TemplateService.getInstance().getQuestionById(body.questionId);
            if (question == null) {
                json(res, BaseResponse.builder().ok(false).msg("问题 ID 不存在").build());
                return;
            }
            if (!question.getType().isChoice()) {
                json(res, BaseResponse.builder().ok(false).msg("该问题不是选择题").build());
                return;
            }

            TemplateService.getInstance().setChoice(body.questionId, body.names);
        } catch (Exception e) {
            json(res, BaseResponse.builder().ok(false).msg("创建失败").error(e.getMessage()).build());
        }

        json(res, BaseResponse.builder().ok(true).build());
    }
}
